(function() {

Ext.onReady(startApp);

var dialog;
var ctx;

function startApp() {
  if (!window.parent.ubqCtx) {
    setTimeout(arguments.callee, 500);
    return;
  }
  ctx = window.parent.ubqCtx;

  dialog = createDialog();
  dialog.show();

  startExtract();
}

function startExtract() {
  ctx.mextractr.extract(ctx.text, function(result) {
    if (result.whos.length>0) {
      var sosl = 
        'FIND {'+result.whos.map(function(w){ 
          return w.value.replace(/さん$/,'') 
        }).join(' OR ')+'}'+
        ' RETURNING Lead(Id,Name,Company,Email ORDER BY LastActivityDate DESC LIMIT 10),'+
        ' Contact(Id,Name,Account.Name,Email ORDER BY LastActivityDate DESC LIMIT 10),'+
        ' Account(Id,Name ORDER BY LastActivityDate DESC LIMIT 10)';
      ctx.sforce.connection.search(sosl, function(res) {
        if (!res.getArray) return;
        var records = res.getArray('searchRecords').map(function(r){ return r.record });
        var leadcontacts = records.filter(function(r){ 
          return r.type=='Lead' || r.type=='Contact';
        }).map(function(r){ return [r.Id, r.Name,r.Company||r.Account.Name,r.Email] });
        if (leadcontacts.length>0) {
          var plist = dialog.getComponent('metadataSub').getComponent('personList');
          plist.getStore().loadData(leadcontacts);
          plist.enable();
        }
        var accounts = records.filter(function(r){ return r.type=='Account' }).map(function(r){
          return [r.Id, r.Name ];
        });
        if (accounts.length>0) {
          var clist = dialog.getComponent('metadataSub').getComponent('companyList');
          clist.getStore().loadData(accounts);
          clist.enable();
        }
      });
    }

    if (result.whens.length>0) {
      var dlist = dialog.getComponent('metadataSub').getComponent('dateList');
      dlist.getStore().loadData(result.whens.map(function(w) { return [w.value, w.startTime] }));
      dlist.enable();
    }

    if (result.wheres.length>0) {
      var llist = dialog.getComponent('metadataSub').getComponent('locList');
      llist.getStore().loadData(result.wheres.map(function(w) { return [w.value] }));
      llist.enable();
    }

  });

  dialog.getComponent('form').getComponent('subject').setValue(ctx.text.split(/\n/)[0]);
  dialog.getComponent('form').getComponent('description').setValue(ctx.text);
}

function createDialog() {
  return new Ext.Window({
    shim : false,
    modal : true,
    plain : true,
    y : 100,
    width : 800, height : 400,
    layout: 'border',
    items : [{
      region : 'east',
      title : '抽出されたメタデータ',
      itemId : 'metadataSub',
      layout : 'accordion',
      layoutConfig : { animate : true },
      width : 200,
      collapsible : true,
      split : true,
      items : [{
        title : '取引先責任者／リード',
        xtype : 'grid',
        itemId : 'personList',
        autoScroll : true,
        disabled : true,
        store : new Ext.data.SimpleStore({
          data : [],
          fields : ['id','name','company','email']
        }),
        hideHeaders : true,
        columns : [{ 
          header : '', dataIndex : '', renderer : function(v, metadata, record) {
            return '<h2>'+record.get('name')+'</h2>'+
                   '<strong>('+record.get('email')+')</strong><br />'+
                   '<i>'+record.get('company')+'</i>';
          }
        }],
        selModel : new Ext.grid.RowSelectionModel({ singleSelect : true }),
        viewConfig : { forceFit : true },
        listeners : {
          rowclick : function(grid) {
            var record = grid.getSelectionModel().getSelected()
            if (record) {
              var form = dialog.getComponent('form').getComponent('relanddate').getComponent('relform');
              form.getComponent('relateId').setValue(record.get('id'));
              form.getComponent('relateName').setValue(record.get('name'));
            }
          }
        }
      }, {
        title : '取引先',
        xtype : 'grid',
        itemId : 'companyList',
        autoScroll : true,
        disabled : true,
        store : new Ext.data.SimpleStore({
          data : [],
          fields : ['id','name']
        }),
        hideHeaders : true,
        columns : [{ 
          header : '', dataIndex : 'name'
        }],
        viewConfig : { forceFit : true },
        selModel : new Ext.grid.RowSelectionModel({ singleSelect : true }),
        listeners : {
          rowclick : function(grid) {
            var record = grid.getSelectionModel().getSelected()
            if (record) {
              var form = dialog.getComponent('form').getComponent('relanddate').getComponent('relform');
              form.getComponent('relateId').setValue(record.get('id'));
              form.getComponent('relateName').setValue(record.get('name'));
            }
          }
        }
      }, {
        title : '日時',
        xtype : 'grid',
        itemId : 'dateList',
        autoScroll : true,
        disabled : true,
        store : new Ext.data.SimpleStore({
          data : [],
          fields : ['value', 'date']
        }),
        hideHeaders : true,
        columns : [{ 
          header : '', dataIndex : '', renderer : function(v, meta, record) {
            return '<h2>'+record.get('value')+'</h2>'+ '('+record.get('date')+')';
          }
        }],
        viewConfig : { forceFit : true },
        selModel : new Ext.grid.RowSelectionModel({ singleSelect : true }),
        listeners : {
          rowclick : function(grid) {
            var record = grid.getSelectionModel().getSelected()
            if (record) {
              var form = dialog.getComponent('form').getComponent('relanddate').getComponent('dateform');
              form.getComponent('date').setValue(record.get('date'));
            }
          }
        }

      }]
    }, {
      xtype : 'form',
      itemId : 'form',
      region : 'center',
      border : false,
      frame : true,
      labelWidth : 70,
      defaults : { anchor : '100%' },
      items : [{
        xtype : 'textfield',
        itemId : 'subject',
        fieldLabel : '件名'
      },  {
        itemId : 'relanddate',
        layout : 'column',
        items : [{
          itemId : 'relform',
          columnWidth : .5,
          layout : 'form',
          items : [{
            xtype : 'textfield',
            itemId : 'relateName',
            fieldLabel : '関連先',
            anchor : '100%',
            disabled : true
          }, {
            xtype : 'hidden',
            itemId : 'relateId'
          }]
        }, {
          width : 30,
          html : '&#160;'
        }, {
          itemId : 'dateform',
          columnWidth : .5,
          layout : 'form',
          items : {
            xtype : 'datefield',
            itemId : 'date',
            format : 'Y/m/d',
            anchor : '100%',
            fieldLabel : '日付'
          }
        }]
      }, {
        xtype : 'textarea',
        itemId : 'description',
        anchor : '100% 100%',
        hideLabel : true
      }],
      buttons : [{
        text : '送信',
        handler : handleSubmit
      }, {
        text : 'キャンセル',
        handler : closeDialog
      }]
    }],
    listeners : { 'close' : closeFrame }
  });
}

function handleSubmit() {
  var form = dialog.getComponent('form');
  var task = new ctx.sforce.SObject('Task');
  task.Subject = form.getComponent('subject').getValue();
  var relateId = form.getComponent('relanddate').getComponent('relform').getComponent('relateId').getValue();
  task[relateId.indexOf('001')==0 ? 'WhatId' : 'WhoId'] = relateId;
  task.ActivityDate = form.getComponent('relanddate').getComponent('dateform').getComponent('date').getValue();
  task.Description = form.getComponent('description').getValue();
  dialog.disable();
  ctx.sforce.connection.create([task], function(ret) {
    if (ret[0].getBoolean('success')) {
      var sfdcUrl = ctx.sforce.connection.serverUrl.split('/').slice(0, 3).join('/');
      window.open(sfdcUrl+'/'+ret[0].id);
      dialog.close();
    } else {
      dialog.enable();
      Ext.Msg.alert('Error'+ret[0].toString());
    }
  })
}

function closeDialog() {
  dialog.close();
}

function closeFrame() {
  window.parent.setTimeout(function() {
    var ifr = window.parent.document.getElementById('_ubiquity_ifr');
    if (ifr) ifr.parentNode.removeChild(ifr);
  }, 1000);
}

})();
